package com.qiuling.iot.entity;

import com.alibaba.fastjson.JSONObject;
import com.qiuling.iot.Exception.code.FunctionCodeEnum;
import com.qiuling.iot.vo.resp.ServerReceiveRespVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Date;

/**
 * @Author：zhangqiang
 * @Description：
 * @Date：Created in 16:29 2020/2/23
 * @Modified By：
 */
@Slf4j
@Data
public class SocketClient {
    private Socket socket;

    private Date lastOnTime;

    public SocketClient(InetAddress ip, int port) {
        try {
            socket = new Socket(ip, port);
            socket.setKeepAlive(true);
        } catch (ConnectException e) {
            log.error("socket创建失败");
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public void println(String message) {
        PrintWriter writer;
        try {
            writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
            writer.println(message);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        }
    }

    /**
     * This function blocks.
     *
     * @return
     */
    public String readLine() throws Exception {
        BufferedReader reader;
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        return reader.readLine();
    }

    /**
     * Ready for use.
     */
    public void close() {
        try {
            // Send a message to tell the server to close the connection.
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
            ServerReceiveRespVO vo = new ServerReceiveRespVO();
            vo.setFunctionCode(FunctionCodeEnum.CLOSE.getValue());
            writer.println(JSONObject.toJSONString(vo));

            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        }
    }

}
